package org.chimi.rr4s.setup;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.simplericity.datadirlocator.DataDirectoryLocator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SetupController {

	private Logger logger = Logger.getLogger(getClass());

	private ContextReloader contextReloader;
	private DataDirectoryLocator dataDirectoryLocator;

	@RequestMapping("/home")
	public String home() {
		return "redirect:/setup/home";
	}

	@RequestMapping("/setup/home")
	public String setuphome() {
		return "setup/home";
	}

	@RequestMapping(value = "/setup/step1", method = RequestMethod.GET)
	public String step1(ModelMap modelMap) {
		modelMap.addAttribute("command", new SetupCommand());
		return "setup/step1";
	}

	@RequestMapping(value = "/setup/step1", method = RequestMethod.POST)
	public String validatestep1(
			@ModelAttribute("command") SetupCommand command,
			BindingResult errors, ModelMap modelMap) {
		// Neo4j 임베드인 경우 해당 디렉토리 접근 가능 여부 확인
		// Neo4j REST인 경우 해당 Neo4j 서버 접근 가능 여부 확인
		return "setup/step1";
	}

	@RequestMapping(value = "/setup/step2", method = RequestMethod.POST)
	public String step2(@ModelAttribute("command") SetupCommand command) {
		return "setup/step2";
	}

	@RequestMapping(value = "/setup/complete", method = RequestMethod.POST)
	public String complete(@ModelAttribute("command") SetupCommand command)
			throws FileNotFoundException, IOException {
		saveConfig();
		// DB 생성 여부를 지정한 경우 테스트 DB 생성
		logger.info("Configuration completed.");
		
		contextReloader.reloadContext();
		logger.info("Context reloaded.");
		return "setup/completed";
	}

	private void saveConfig() throws FileNotFoundException, IOException {
		FileOutputStream fos = new FileOutputStream(new File(
				dataDirectoryLocator.locateDataDirectory(), "conf.properties"));
		Properties prop = new Properties();
		prop.store(fos, "");
		fos.close();
		System.out.println("설정 저장");
	}

	public void setContextReloader(ContextReloader contextReolader) {
		this.contextReloader = contextReolader;
	}

	public void setDataDirectoryLocator(
			DataDirectoryLocator dataDirectoryLocator) {
		this.dataDirectoryLocator = dataDirectoryLocator;
	}

}
